package contratosonline.jpa.controller;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;

import contratosonline.entity.Campus;
import contratosonline.entity.FiscalContrato;
import contratosonline.entity.Setor;

import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author admin
 */
public class SetorJPAController{
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

	public SetorJPAController(){
		emf = Persistence.createEntityManagerFactory("ContratosOnLinePU");
	}

    /* (non-Javadoc)
	 * @see contratosonline.ejb.controller.SetorControllerLocal#persiste(contratosonline.entity.Setor)
	 */
    public void persiste(Setor setor) {
        if (setor.getFiscalcontratoCollection() == null) {
            setor.setFiscalcontratoCollection(new ArrayList<FiscalContrato>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Campus campus = setor.getCampus();
            if (campus != null) {
                campus = em.getReference(campus.getClass(), campus.getIdCampus());
                setor.setCampus(campus);
            }
            Collection<FiscalContrato> attachedFiscalcontratoCollection = new ArrayList<FiscalContrato>();
            for (FiscalContrato fiscalcontratoCollectionFiscalcontratoToAttach : setor.getFiscalcontratoCollection()) {
                fiscalcontratoCollectionFiscalcontratoToAttach = em.getReference(fiscalcontratoCollectionFiscalcontratoToAttach.getClass(), fiscalcontratoCollectionFiscalcontratoToAttach.getIdFiscalContrato());
                attachedFiscalcontratoCollection.add(fiscalcontratoCollectionFiscalcontratoToAttach);
            }
            setor.setFiscalcontratoCollection(attachedFiscalcontratoCollection);
            em.persist(setor);
            if (campus != null) {
                campus.getSetorCollection().add(setor);
                campus = em.merge(campus);
            }
            for (FiscalContrato fiscalcontratoCollectionFiscalcontrato : setor.getFiscalcontratoCollection()) {
                Setor oldSetorOfFiscalcontratoCollectionFiscalcontrato = fiscalcontratoCollectionFiscalcontrato.getSetor();
                fiscalcontratoCollectionFiscalcontrato.setSetor(setor);
                fiscalcontratoCollectionFiscalcontrato = em.merge(fiscalcontratoCollectionFiscalcontrato);
                if (oldSetorOfFiscalcontratoCollectionFiscalcontrato != null) {
                    oldSetorOfFiscalcontratoCollectionFiscalcontrato.getFiscalcontratoCollection().remove(fiscalcontratoCollectionFiscalcontrato);
                    oldSetorOfFiscalcontratoCollectionFiscalcontrato = em.merge(oldSetorOfFiscalcontratoCollectionFiscalcontrato);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    /* (non-Javadoc)
	 * @see contratosonline.ejb.controller.SetorControllerLocal#altera(contratosonline.entity.Setor)
	 */
    public void altera(Setor setor) throws Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Setor persistentSetor = em.find(Setor.class, setor.getIdSetor());
            Campus campusOld = persistentSetor.getCampus();
            Campus campusNew = setor.getCampus();
            Collection<FiscalContrato> fiscalcontratoCollectionOld = persistentSetor.getFiscalcontratoCollection();
            Collection<FiscalContrato> fiscalcontratoCollectionNew = setor.getFiscalcontratoCollection();
            if (campusNew != null) {
                campusNew = em.getReference(campusNew.getClass(), campusNew.getIdCampus());
                setor.setCampus(campusNew);
            }
            Collection<FiscalContrato> attachedFiscalcontratoCollectionNew = new ArrayList<FiscalContrato>();
            for (FiscalContrato fiscalcontratoCollectionNewFiscalcontratoToAttach : fiscalcontratoCollectionNew) {
                fiscalcontratoCollectionNewFiscalcontratoToAttach = em.getReference(fiscalcontratoCollectionNewFiscalcontratoToAttach.getClass(), fiscalcontratoCollectionNewFiscalcontratoToAttach.getIdFiscalContrato());
                attachedFiscalcontratoCollectionNew.add(fiscalcontratoCollectionNewFiscalcontratoToAttach);
            }
            fiscalcontratoCollectionNew = attachedFiscalcontratoCollectionNew;
            setor.setFiscalcontratoCollection(fiscalcontratoCollectionNew);
            setor = em.merge(setor);
            if (campusOld != null && !campusOld.equals(campusNew)) {
                campusOld.getSetorCollection().remove(setor);
                campusOld = em.merge(campusOld);
            }
            if (campusNew != null && !campusNew.equals(campusOld)) {
                campusNew.getSetorCollection().add(setor);
                campusNew = em.merge(campusNew);
            }
            for (FiscalContrato fiscalcontratoCollectionOldFiscalcontrato : fiscalcontratoCollectionOld) {
                if (!fiscalcontratoCollectionNew.contains(fiscalcontratoCollectionOldFiscalcontrato)) {
                    fiscalcontratoCollectionOldFiscalcontrato.setSetor(null);
                    fiscalcontratoCollectionOldFiscalcontrato = em.merge(fiscalcontratoCollectionOldFiscalcontrato);
                }
            }
            for (FiscalContrato fiscalcontratoCollectionNewFiscalcontrato : fiscalcontratoCollectionNew) {
                if (!fiscalcontratoCollectionOld.contains(fiscalcontratoCollectionNewFiscalcontrato)) {
                    Setor oldSetorOfFiscalcontratoCollectionNewFiscalcontrato = fiscalcontratoCollectionNewFiscalcontrato.getSetor();
                    fiscalcontratoCollectionNewFiscalcontrato.setSetor(setor);
                    fiscalcontratoCollectionNewFiscalcontrato = em.merge(fiscalcontratoCollectionNewFiscalcontrato);
                    if (oldSetorOfFiscalcontratoCollectionNewFiscalcontrato != null && !oldSetorOfFiscalcontratoCollectionNewFiscalcontrato.equals(setor)) {
                        oldSetorOfFiscalcontratoCollectionNewFiscalcontrato.getFiscalcontratoCollection().remove(fiscalcontratoCollectionNewFiscalcontrato);
                        oldSetorOfFiscalcontratoCollectionNewFiscalcontrato = em.merge(oldSetorOfFiscalcontratoCollectionNewFiscalcontrato);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = setor.getIdSetor();
                if (findSetor(id) == null) {
                    throw new Exception("The setor with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    /* (non-Javadoc)
	 * @see contratosonline.ejb.controller.SetorControllerLocal#exclui(java.lang.Integer)
	 */
    public void exclui(Integer id) throws Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Setor setor;
            try {
                setor = em.getReference(Setor.class, id);
                setor.getIdSetor();
            } catch (EntityNotFoundException enfe) {
                throw new Exception("The setor with id " + id + " no longer exists.", enfe);
            }
            Campus campus = setor.getCampus();
            if (campus != null) {
                campus.getSetorCollection().remove(setor);
                campus = em.merge(campus);
            }
            Collection<FiscalContrato> fiscalcontratoCollection = setor.getFiscalcontratoCollection();
            for (FiscalContrato fiscalcontratoCollectionFiscalcontrato : fiscalcontratoCollection) {
                fiscalcontratoCollectionFiscalcontrato.setSetor(null);
                fiscalcontratoCollectionFiscalcontrato = em.merge(fiscalcontratoCollectionFiscalcontrato);
            }
            em.remove(setor);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    /* (non-Javadoc)
	 * @see contratosonline.ejb.controller.SetorControllerLocal#findSetorEntities()
	 */
    public List<Setor> findSetorEntities() {
        return findSetorEntities(true, -1, -1);
    }

    /* (non-Javadoc)
	 * @see contratosonline.ejb.controller.SetorControllerLocal#findSetorEntities(int, int)
	 */
    public List<Setor> findSetorEntities(int maxResults, int firstResult) {
        return findSetorEntities(false, maxResults, firstResult);
    }

    @SuppressWarnings("unchecked")
	private List<Setor> findSetorEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Setor as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    /* (non-Javadoc)
	 * @see contratosonline.ejb.controller.SetorControllerLocal#findSetor(java.lang.Integer)
	 */
    public Setor findSetor(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Setor.class, id);
        } finally {
            em.close();
        }
    }

    /* (non-Javadoc)
	 * @see contratosonline.ejb.controller.SetorControllerLocal#getSetorCount()
	 */
    public int getSetorCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Setor as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}

